<template>
  <div class="rainfall-container p-4 font-sans px-[346px]">
    <!-- 未来2小时降水趋势图 -->
    <div class="trend-chart bg-blue-50 rounded-xl p-4 mb-6 text-center">
      <h3 class="text-lg font-semibold text-gray-800">{{ summary }}</h3>
      <div ref="chartRef" class="chart-container w-full h-48 mt-4 mb-2"></div>
      <div class="update-time text-xs text-gray-500 mt-1">更新时间：{{ updateTime }}</div>
    </div>

    <!-- 过去24小时降水排行 -->
    <div class="rank-list bg-gray-100 rounded-xl p-4">
      <h3 class="text-center text-lg font-semibold text-gray-800 mb-4">过去24小时城市降水</h3>
      <ul class="list-none p-0 ">
        <li
          v-for="(city, index) in topRainCities"
          :key="index"
          class=" py-2 border-b border-gray-200 last:border-b-0"
          :class="'bg-blue-50 font-bold' "
        >
          <span class="rank flex items-center justify-center w-6 h-6 rounded-full text-xs text-white">
            {{ index + 1 }}
          </span>
          <div class="flex items-center justify-between">
            <span class="text-sm">{{ city.name }}, {{ city.province }}</span>
            <span class="precip font-bold text-blue-600">{{ city.precip }}mm</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

const userLatitude = ref(null);
const userLongitude = ref(null);

// 用于存储分钟级降水数据
const trendData = ref([]);
const summary = ref("");
const updateTime = ref("");

// 降水排行数据
const topRainCities = ref([]);

// ECharts 实例
const chartRef = ref(null);
let chartInstance = null;

// 初始化定位
onMounted(() => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        userLatitude.value = position.coords.latitude.toFixed(2);
        userLongitude.value = position.coords.longitude.toFixed(2);
        fetchRecentRainfall(userLongitude.value, userLatitude.value);
      },
      (error) => {
        console.log("定位失败:", error);
      },
      { enableHighAccuracy: true }
    );
  }
});

async function fetchRecentRainfall(longitude, latitude) {
  const host = "https://p76yvxv44n.re.qweatherapi.com";
  const token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";

  try {
    // 🌧️ 获取分钟级降水数据（/v7/minutely/5m）
    const minutelyResponse = await axios.get(`${host}/v7/minutely/5m`, {
      params: { location: `${longitude},${latitude}` },
      headers: { Authorization: token },
    });

    const data = minutelyResponse.data;

    if (data.code === "200") {
      // 设置摘要和更新时间
      summary.value = data.summary;
      updateTime.value = data.updateTime;

      // 提取前24个5分钟数据点（约2小时）
      trendData.value = data.minutely.slice(0, 24).map((item) => ({
        fxTime: item.fxTime,
        precip: parseFloat(item.precip),
        type: item.type,
      }));

      // 渲染图表
      renderChart();
    }

    // 🔍 获取预警列表中的城市ID
    const listResponse = await axios.get(`${host}/v7/warning/list`, {
      params: { range: "cn" },
      headers: { Authorization: token },
    });

    const locationIds = listResponse.data.warningLocList
      .map((loc) => loc.locationId)
      .slice(0, 10);

    // 并发请求每个城市的当前天气数据
    const promises = locationIds.map(async (id) => {
      try {
        const warningRes = await axios.get(`${host}/v7/weather/now`, {
          params: { location: id },
          headers: { Authorization: token },
        });

        const geoRes = await axios.get(`/api/geo/v2/city/lookup`, {
          params: { location: id },
          headers: { Authorization: token },
        });

        const cityName = geoRes.data.location[0]?.name || "未知城市";
        const province = geoRes.data.location[0]?.adm1 || "未知省份";
        const precip = parseFloat(warningRes.data.now?.precip || 0); // 过去1小时降水量

        return { name: cityName, province, precip };
      } catch (err) {
        console.warn(`获取城市 ${id} 数据失败`, err);
        return null;
      }
    });

    const citiesData = await Promise.all(promises);
    topRainCities.value = citiesData
      .filter((city) => city !== null)
      .sort((a, b) => b.precip - a.precip)
      .slice(0, 10);
  } catch (error) {
    console.error("获取降水数据失败:", error.response?.data || error.message);
  }
}

function renderChart() {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  // 简化时间轴：只显示“现在”、“60min”、“2小时”
  const xAxisData = [
    "现在",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "60min",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "2小时",
  ];
  const seriesData = trendData.value.map((item) => item.precip);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: (params) => {
        const time = params[0].axisValue;
        const value = params[0].value;
        return `${time}<br/>降水量: ${value}mm`;
      },
    },
    grid: {
      left: "10%",
      right: "10%",
      bottom: "20%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 10,
        color: "#666",
      },
      axisLine: {
        lineStyle: {
          color: "#e0e0e0",
        },
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      type: "value",
      name: "mm",
      axisLabel: {
        formatter: "{value}",
        color: "#666",
      },
      axisLine: {
        lineStyle: {
          color: "#e0e0e0",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#f0f0f0",
        },
      },
    },
    series: [
      {
        name: "降水量",
        type: "bar",
        barWidth: "10px",
        data: seriesData,
        itemStyle: {
          color: "#1890ff",
        },
        emphasis: {
          itemStyle: {
            color: "#0066cc",
          },
        },
      },
    ],
  };

  chartInstance.setOption(option);
}

// 销毁图表实例
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>